<template>
    <div class="locationSetMap-outer">
        <div id="locationSetMap"></div>
        <!-- 左上侧的搜索框 -->
        <div class="searchDom">
            <poiSearch :poiSelClick='showLocatePoint'></poiSearch>
        </div>
    </div>
</template>
<script setup lang="ts">
import { initMap } from '@/utils/map/leafletMap';
import { isArray } from '@/utils/validate.js';
import { wgs84togcj02, gcj02towgs84 } from "@/utils/map/coordinateTransfor.js"
import { getMinAdsByPoi } from "@/utils/map/leafletMap.js"
let map = null, // 地图
    _graph, // 点图层
    result: {
        lng: string,
        lat: string,
        address: string,
    } = {
        lng: null,
        lat: null,
        address: null,
    }; // 选中的点经纬度
function showLocatePoint(obj) {
    const [lng, lat] = gcj02towgs84(obj.lng, obj.lat)
    result.lng = lng + '';
    result.lat = lat + '';
    result.address = obj.address;
    model.value = result
    map.flyTo(result, 17, { animate: false }); //同时设置地图层级与中心点
    setMarker(result);
}
function setMarker({ lng, lat }) {
    if (_graph) _graph.setLatLng([lat, lng])
    else _graph = L.marker([lat, lng]).addTo(map)
}
const model = defineModel() as any;
if (isArray(model.value)) {
    if (model.value.length > 0) {
        model.value = model.value[0]
    } else {
        model.value = null;
    }
}
onMounted(() => {
    // 地图初始化
    nextTick(() => {
        initMap("locationSetMap").then(_map => {
            map = _map;
            _map.on('click', async (e) => {
                setResult(e.latlng)
            })
            if (model.value) {
                setMarker(model.value);
                map.flyTo(model.value, 17, { animate: false }); //同时设置地图层级与中心点
            }
        });
    })
})
async function setResult({ lng, lat }) {
    let _point = wgs84togcj02(lng, lat)
    let res: any = await getMinAdsByPoi({
        lng: _point[0],//城市权重优先
        lat: _point[1],
    });
    if (res.code == 200) {
        result.lng = lng;
        result.lat = lat;
        result.address = res.data;
        model.value = result
        setMarker(result);
    }
}
</script>
<style lang='scss' scoped>
.locationSetMap-outer {
    position: relative;
    width: 100%;
    height: 100%;

    .searchDom {
        position: absolute;
        top: 20px;
        left: 20px;
        width: 220px;
        z-index: 500;
    }
}

#locationSetMap {
    width: 100%;
    height: 100%;
}
</style>